<!--
 * @Description:div拖拽高级应用
 * @Author: Sun
 * @Date: 2019-07-01 20:05:50
 * @LastEditors: Sun
 * @LastEditTime: 2019-07-09 06:31:08
 -->
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>div拖拽</title>
	<style>
		#div1 {
			width: 100px;
			height: 100px;
			background: red;
			position: absolute;
		}
		#div2 {
		width: 400px;
		height: 300px;
		background:#dcdcdc;
		position:relative;
		margin: 20px auto
		}
	</style>
	<script>
		window.onload = function () {
			var odiv = document.getElementById("div1")
			var odiv2 = document.getElementById("div2")
			var disX = 0;
			var disY = 0;
			odiv.onmousedown = function (ev) {
				var oEvent = ev || event;
				disX = oEvent.clientX - odiv.offsetLeft;
				disY = oEvent.clientY - odiv.offsetTop;
				
				document.onmousemove = function (ev) {
					var oEvent = ev || event;
					console.log(oEvent.clientX+"-"+oEvent.clientY+"-"+disY)
					// i t 是鼠标距离div的内部距离
					var i = oEvent.clientX - disX
					var t = oEvent.clientY - disY
					if (i < 0) { //窗口的可视区域-div的宽度
						i = 0 //就是鼠标在方块内能移动的最大距离
					} else if (i >odiv2.offsetWidth - odiv.offsetWidth) {
						i = odiv2.offsetWidth - odiv.offsetWidth
					}
					if (t < 0) {
						t = 0
					}else if(t>odiv2.offsetHeight - odiv.offsetHeight){
						t= odiv2.offsetHeight - odiv.offsetHeight
					}
					odiv.style.left = i + 'px';
					odiv.style.top = t + 'px';
				}
				document.onmouseup = function () {
					document.onmousemove = null
					document.onmouseup = null
				}
				return false;
			}
		}
	</script>
</head>

<body>
	<div id="div2">
		<div id="div1">
			<span>分享到</span>
		</div>
	</div>
</body>

</html>